package de.grosjohann.android.feuerwehr.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import de.grosjohann.android.feuerwehr.R;
import de.grosjohann.android.feuerwehr.WeatherActivity;
import de.grosjohann.android.feuerwehr.util.FileUtil;
import de.grosjohann.android.feuerwehr.util.PrefsUtil;
import de.grosjohann.android.feuerwehr.webservice.WeatherWsFacade;

public class WeatherNotificationService
  extends IntentService {
  public static final String WEATHER_DATA = "feuerwehr.WeatherData";

  public static final int FMS_SERVICE_NOTIFICATION_ID = 112;

  private static final String NAME = "WeatherNotificationService";

  private Notification notification = null;

  public WeatherNotificationService() {
    super(NAME);
  }

  @Override
  public void onCreate() {
    super.onCreate();

    Log.d(NAME, "create");

    // Notification aufbauen
    notification = new Notification();
    notification.tickerText = getString(R.string.lblWeatherNotificationTickerText);
    notification.icon = R.drawable.notificon;
  }

  @Override
  protected void onHandleIntent(Intent newIntent) {

    Log.d(NAME, "handle");

    Context context = getApplicationContext();

    try {
      String json = WeatherWsFacade.getWeather(context);
      String lastReceive = FileUtil.readFile(context, WEATHER_DATA);

      if (json != null && !json.equals(lastReceive)) {

        FileUtil.writeFile(context, WEATHER_DATA, json);
        Log.i(NAME, "new Data: " + json);

        if (PrefsUtil.getBoolean(context, R.string.prefKeyNotification, false)) {
          Intent notificationIntent = new Intent(context, WeatherActivity.class);

          PendingIntent contentIntent =
              PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

          // expanded message title
          CharSequence contentTitle = getString(R.string.appName);

          // expanded message text
          CharSequence contentText = getString(R.string.lblWeatherNotificationTickerText);

          notification.when = System.currentTimeMillis();

          notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

          NotificationManager mNotificationManager =
              (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          mNotificationManager.notify(FMS_SERVICE_NOTIFICATION_ID, notification);
        }
      }

    } catch (Exception ex) {
      Log.e(NAME, ex.getMessage(), ex);
    }
  }
}
